<template>
	<view style="background-color: #111111;">
		<view v-if="loading" class="mask" :style="{ height: scroll_h + 'px' }"> </view>
		<view @touchstart="hideDrawer" class="x-scroll" :style="{ height: scroll_h + 'px' }">
			<scroll-view id="scrollview" :scroll-top="scrollTop" :scroll-with-animation="true"
				refresher-background="#111111" :scroll-y="true" :scroll-anchoring="true" class="scroll-wrap"
				:style="{ height: scroll_h + 'px' }">
				<view id="msglistview">
					<block v-for="(l, i) in list" :key="i">
						<!-- 时间轴 -->
						<view v-if="l.type === 0" class="chat-time">{{ l.time }}</view>
						<!-- 自定义消息 -->
						<custom v-else-if="l.type === 200" :cdata="l" @customEvent="customEvent($event, i)"></custom>
						<view v-else :class="{ 'flex-flow': l.direction === 0 }" class="chat-item">
							<view class="chat-head">
								<!-- 对象头像 -->
								<image v-if="l.direction === 1"
									@click="toRoute(`/pages/user/user_visitor?id=${uID(l.senderUserID)}`)"
									:src="l.userAvatarUrl" mode="aspectFill"></image>
								<!-- 自己头像 -->
								<image v-else :src="l.userAvatarUrl"
									@click="toRoute(`/pages/user/user_visitor?id=${uID(l.senderUserID)}`)"
									mode="aspectFill"></image>
							</view>
							<!-- 文本消息 -->
							<view v-if="l.type === 1" class="chat-content">
								<text selectable="true" user-select="true">{{ l.message }}</text>
								<!-- <image v-if="l.fail" class="chat-error"
									src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/fail.png"> </image> -->
							</view>
							<!-- 图片 -->
							<view v-else-if="l.type === 11" class="chat-imgs"
								:style="{ width: l.thumbWidth + 'px', height: l.thumbHeight + 'px' }">
								<image @click="previewImage(l.url)" :src="l.url" mode="aspectFill"> </image>
							</view>
							<!-- 音频 -->
							<view v-else-if="l.type === 13" @click="playAudio(l.url, i)"
								:style="{ width: `${getAudioWidth(l.duration)}rpx` }" class="chat-content chat-audio">
								<block v-if="l.direction == 0">{{ l.duration }}<span>"</span>
									<view class="wifi-symbol" :class="{ animation: playMsg.i == i && playMsg.play == 0 }">
										<view class="wifi-circle first"></view>
										<view class="wifi-circle second"></view>
										<view class="wifi-circle third"></view>
									</view>
								</block>
								<block v-else>
									<view class="wifi-symbol direction"
										:class="{ animation: playMsg.i == i && playMsg.play == 0 }">
										<view class="wifi-circle first"></view>
										<view class="wifi-circle second"></view>
										<view class="wifi-circle third"></view>
									</view>{{ l.duration }}<span>"</span>
								</block>
							</view>
						</view>
					</block>
					<view class="fit-bottom"> </view>
				</view>
			</scroll-view>
		</view>
		<view id="bottom" class="chat-body">
			<view class="chat-panel">
				<view class="phrBox">
					<view class="panel-item" v-for="(item, index) in phrasesList" :key="index" @click.prevent="sendPhrases(item)">
						<!-- <uni-icons type="chat-filled" size="26" color="#40bd66"></uni-icons> -->
						<!-- {{item}} -->
						<text>{{item}}</text>
					</view>
				</view>
				<view @click.prevent="addWX" class="panel-item">
					<uni-icons type="weixin" size="26" color="#40bd66"></uni-icons>
					<text>加微信</text>
				</view>
				<view @click.prevent="$refs['memberCard'].open()" class="panel-item">
					<uni-icons type="vip-filled" size="26" color="#ff5500"></uni-icons>
					<text>送会员</text>
				</view>
			</view>
			<view class="chat-cell">
				<view @click="changeEvent" class="chat-switch">
					<image v-if="changeType === 2" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/text.png"
						mode="">
					</image>
					<image v-if="changeType === 1" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/voice.png"
						mode="">
					</image>
				</view>
				<view v-if="changeType === 1" class="chat-input">
					<textarea auto-height="true" confirm-type="send" :confirm-hold="true"
						:disable-default-padding="true" cursor-spacing="15" :hold-keyboard="true"
						:show-confirm-bar="false" :adjust-position="false" v-model="content" @linechange="linechange"
						@confirm="sendEvent" @click="openDrawer" :focus="focus"></textarea>
				</view>
				<record v-if="changeType === 2" style="flex: 1;" @record="sendRecord"></record>
				<view @click="menuEvent" class="box-add">
					<uni-icons type="plus" color="#000000" size="34"></uni-icons>
				</view>
				<view v-if="changeType === 1" class="chat-send" @touchend.prevent="sendEvent"> 发送 </view>
			</view>
			<view style="transition: height 0.2s;" :style="{ height: height + 'px' }">
				<!-- 功能菜单 -->
				<view v-if="isMenu" class="chat-menu" :style="{ height: height + 'px' }">
					<view class="menu-wrap">
						<view @click="sendImage('album')" class="menu-cell">
							<view class="menu-icon">
								<uni-icons type="image" size="34" color="#1F1F1F" />
							</view>
							<text>相册</text>
						</view>
						<view @click="sendImage('camera')" class="menu-cell">
							<view class="menu-icon">
								<uni-icons type="camera-filled" size="34" color="#1F1F1F" />
							</view>
							<text>拍摄</text>
						</view>
						<view class="menu-cell" @click="addWX">
							<view class="menu-icon">
								<uni-icons type="weixin" size="34" color="#1F1F1F" />
							</view>
							<text>加微信</text>
							<view class="menu-tips">会员专享</view>
						</view>
						<!-- <view class="menu-cell" @click="$refs['gift'].open()">
							<view class="menu-icon">
								<uni-icons type="gift-filled" size="34" color="#1F1F1F" />
							</view>
							<text>送礼物</text>
						</view> -->
						<view class="menu-cell" @click="$refs['memberCard'].open()">
							<view class="menu-icon">
								<uni-icons type="vip-filled" size="36"></uni-icons>
							</view>
							<text>送会员</text>
						</view>
						<view class="menu-cell"
							@click="nav_to(`/pages/chat/reportlist?id=${userID}&name=${conversationName}`)">
							<view class="menu-icon">
								<uni-icons type="info-filled" size="36"></uni-icons>
							</view>
							<text>举报</text>
						</view>
					</view>
				</view>
			</view>
			<view class="fit-bottom"> </view>
		</view>
		<!-- 礼物赠送弹窗 -->
		<uni-popup ref="gift" type="center">
			<view class="popup">
				<image class="popup-bg" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1710326674977862.png"
					mode="">
				</image>
				<view class="popup-title">
					<view class="title-text"> 礼物赠送 </view>
				</view>
				<image class="popup-close" @click="$refs['gift'].close()"
					src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/del.png" mode=""></image>
				<scroll-view class="popup-wrap" scroll-y="true" :show-crollbar="true" scroll-with-animation="true">
					<view class="x-list">
						<view v-for="(l, i) in gift_list" :key="i" @click="gift_index = i" class="list-cell"
							:class="{ 'list-active': i == gift_index }">
							<image class="list-icon" :src="l.Icon" mode=""></image>
							<view v-if="i != gift_index" class="list-name"> {{ l.Name }} </view>
							<view class="list-price"> ￥{{ l.Price }} </view>
							<view v-if="i == gift_index" @click="giveGift" class="list-btn"> 赠送 </view>
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		<!-- 添加微信非会员权益弹窗 -->
		<uni-popup ref="weixin" type="center">
			<view class="wx_popup" v-if="viptype.length > 0">
				<image class="bg" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1710326674977862.png"
					mode=""></image>
				<view class="del_wxpopup" @click="$refs['weixin'].close()">
					<image class="del" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/del.png" mode=""></image>
				</view>
				<view class="popup_title">
					<view class="title_text">
						查看微信是会员特权
					</view>
				</view>
				<view class="popup_lit">
					开通会员可以无限制加微信
				</view>
				<view class="wx_p_content">
					<view class="price">
						<view :class="['price_item', 'gold_card', member_index == 0 ? 'member-active' : '']"
							@click="member_index = 0">
							<view class="price_type">
								金卡会员
							</view>
							<view class="crown">
								<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/goldcrown.png" mode="">
								</image>
							</view>
							<view class="price_tit">
								{{ viptype[0].Discount == 1 ? viptype[0].Fee : viptype[0].PValue }}元
								<view class="first_vip" v-if="viptype[0].Discount < 1">
									{{ '限时' + (viptype[0].Discount * 10) + '折' }}
								</view>
							</view>
							<!-- <view v-else class="price_tit">
								{{viptype[0].Discount == 1?viptype[0].Fee:viptype[0].PValue}}
							</view> -->
							<!-- <view class="price_lit" v-if="is_first_upgrade" style="text-decoration: line-through;">
								{{viptype[0].Discount == 1?viptype[0].Fee:viptype[0].PValue}}
							</view>
							<view class="price_lit" style="opacity: 0;">
								{{viptype[0].Discount == 1?viptype[0].Fee:viptype[0].PValue}}
							</view> -->
							<view class="price_lit">
								免费加好友、加微信
							</view>
							<view class="active_icon" v-if="member_index == 0">
								<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/check.png" mode="">
								</image>
							</view>
						</view>
						<view :class="['price_item', 'blak_card', member_index == 1 ? 'member-active' : '']"
							@click="member_index = 1">
							<view class="price_type">
								黑卡会员
							</view>
							<view class="crown">
								<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/blackcrown.png" mode="">
								</image>
							</view>
							<view class="price_tit">
								{{ viptype[1].Discount == 1 ? viptype[1].Fee : viptype[1].PValue }}元
								<view class="first_vip" v-if="viptype[1].Discount < 1">
									{{ '限时' + (viptype[1].Discount * 10) + '折' }}
								</view>
							</view>
							<!-- <view v-else class="price_tit">
								{{viptype[1].Fee}}
							</view> -->
							<!-- <view class="price_lit" v-if="is_first_upgrade" style="text-decoration: line-through;">
								{{viptype[1].Discount == 1?viptype[1].Fee:viptype[1].PValue}}
							</view>
							<view class="price_lit" style="opacity: 0;">
								{{viptype[1].Discount == 1?viptype[1].Fee:viptype[1].PValue}}
							</view> -->
							<!-- <view class="price_lit" style="opacity: 0;">
								占位
							</view> -->
							<view class="price_lit">
								定制运动
							</view>
							<view class="active_icon" v-if="member_index == 1">
								<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/check.png" mode="">
								</image>
							</view>
						</view>
					</view>
					<view class="wx_btn">
						<view class="btn_item gold_btn" @click="WXPayment">
							单次付费({{ (nv_price) }}元)
						</view>
						<view class="btn_item black_btn" @click="memberPayment">
							开通会员
						</view>
					</view>
					<view class="vip_tips">
						<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17104053105741351.png" mode="">
						</image>
						如果对方拒绝或超过5天未回应，费用将退回平台余额
					</view>
				</view>
			</view>

		</uni-popup>
		<!-- <uni-popup ref="WXAdd" type="center">
			<view class="popup">
				<image class="popup-bg" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1710326674977862.png" mode="">
				</image>
				<view class="popup-title">
					<view class="title-text"> 加微信是会员特权 </view>
				</view>
				<view class="popup-title-sub">开通会员可以无限制加微信</view>
				<image class="popup-close" @click="$refs['WXAdd'].close()"
					src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/del.png" mode=""></image>
				<scroll-view class="popup-wrap" scroll-y="true" :show-crollbar="true" scroll-with-animation="true">
					<view class="x-member">
						<view @click="member_index=0" class="member-item" :class="{'member-active':member_index===0}">
							<view class="member-title"> 金卡会员 </view>
							<image class="member-icon" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/goldcrown.png" mode="">
							</image>
							<view class="member-price"> ￥500/月 </view>
							<view class="member-desc"> 免费加好友、加微信 </view>
							<image v-if="member_index===0" class="active-icon"
								src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/check.png" mode=""></image>
						</view>
						<view @click="member_index=1" class="member-item black-vip" :class="{'member-active':member_index===1}">
							<view class="member-title"> 黑金卡会员 </view>
							<image class="member-icon" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/goldcrown.png" mode="">
							</image>
							<view class="member-price"> ￥2000/月 </view>
							<view class="member-desc"> 定制球局和线下聚会 </view>
							<image v-if="member_index===1" class="active-icon"
								src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/check.png" mode=""></image>
						</view>
					</view>
				</scroll-view>
				<view class="popup-btn">
					<view class="x-btn btn-a" @click="WXPayment"> 单次付费(￥{{wx_price}}) </view>
					<view class="x-btn btn-b" @click="memberPayment"> 开通会员 </view>
				</view>
				<view class="popup-tips">
					<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17104053105741351.png" mode=""></image>
					如果对方拒绝或超过5天未回应，费用将退回平台余额
				</view>
			</view>
		</uni-popup> -->
		<!-- 添加微信非会员权益弹窗 -->
		<uni-popup ref="WXAddMem" type="center">
			<view class="popup">
				<image class="popup-bg" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1710326674977862.png"
					mode="">
				</image>
				<view class="popup-title">
					<view class="title-text"> 会员特权 </view>
				</view>
				<image class="popup-close" @click="$refs['WXAddMem'].close()"
					src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/del.png" mode=""></image>
				<scroll-view class="popup-wrap" scroll-y="true" :show-crollbar="true" scroll-with-animation="true">
					<view class="weixin-icon">
						<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/wx_logo.png" mode=""></image>
						<view class="weixin-desc">
							申请查看微信后，</br>需等待对方同意后方可查看微信号
						</view>
					</view>
				</scroll-view>
				<view class="popup-btn -btn">
					<view class="x-btn btn-b" @click="sendWXIM"> 免费查看 </view>
				</view>
			</view>
		</uni-popup>
		<!-- 会员卡赠送弹窗 -->
		<uni-popup ref="memberCard" type="center">
			<view class="popup" v-if="viptype.length > 0">
				<image class="popup-bg" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1710326674977862.png"
					mode="">
				</image>
				<view class="popup-title">
					<view class="title-text"> 会员卡赠送 </view>
				</view>
				<view class="popup-title-sub">黑卡包含金卡所有特权</view>
				<image class="popup-close" @click="vipclose"
					src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/del.png" mode=""></image>
				<scroll-view class="popup-wrap" scroll-y="true" :show-crollbar="true" scroll-with-animation="true">
					<view class="x-member">
						<view @click="member_index = 0" class="member-item" :class="{ 'member-active': member_index === 0 }">
							<view class="member-title"> 金卡会员 </view>
							<image class="member-icon"
								src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/goldcrown.png" mode="">
							</image>
							<view class="member-price">{{ viptype[0].Fee }}元</view>
							<view class="member-desc"> 免费加好友、加微信 </view>
							<image v-if="member_index === 0" class="active-icon"
								src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/check.png" mode=""></image>
						</view>
						<view @click="member_index = 1" class="member-item black-vip"
							:class="{ 'member-active': member_index === 1 }">
							<view class="member-title"> 黑卡会员 </view>
							<image class="member-icon"
								src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/goldcrown.png" mode="">
							</image>
							<view class="member-price"> {{ viptype[1].Fee }}元 </view>
							<view class="member-desc"> 定制运动 </view>
							<image v-if="member_index === 1" class="active-icon"
								src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/chat/check.png" mode=""></image>
						</view>
					</view>
				</scroll-view>
				<view class="popup-btn -btn">
					<view class="x-btn btn-b" @click="giveMember"> 豪爽赠送 </view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import record from './record.vue';
import custom from './custom.vue';
import { throttle, sleep, getID } from '@/im/js/utils';
const cVersion = 'V2' //缓存版本号
let that, windowHeight
const delay = 100
export default {
	components: {
		record,
		custom
	},
	data() {
		return {
			viptype: [],
			is_first_upgrade: false,
			Issex: null,
			loading: true,
			isSeek: false,
			keyboardHeight: 0,
			scroll_h: 0,
			conversationID: 0,
			conversationName: '',
			userID: 0,
			isFriend: true,
			list: [],
			userList: [],
			height: 0, //是否显示键盘空白栏目高度
			initBotHeight: 0, //底部初始高度
			minHeight: 0, //聊天窗口最小可视化高度
			isMenu: false, //是否显示功能菜单
			//滚动距离
			scrollTop: 0,
			changeType: 1,
			content: '',
			lineCount: 1,
			focus: false,
			//播放语音相关参数
			AUDIO: uni.createInnerAudioContext(),
			playMsg: { i: -1, play: -1 },

			gift_list: [], //礼物数组
			gift_index: -1, //当前选中礼物
			member_index: 0,
			wx_price: 50, //添加微信单次付费
			nv_price: 10,
			
			
			phrasesList: [],
			textPhrases:'',
		};
	},
	async onLoad(e) {
		let user = uni.getStorageSync('user')
		let res = await this.$api.post('User/GetUserInfo', {
			ID: user.UserID
		});
		this.Issex = res.data.Sex
		console.log(this.Issex);
		let mf_data = await this.$api.post('/Member/IsFirstUpgrade');
		// this.is_first_upgrade = mf_data.data;
		this.GetUserType()
		that = this
		this.isSeek = e.isSeek || false //是否从咨询页面过来的，加问候语
		// setTimeout(() => { this.$refs['gift'].open() }, 2000)
		this.conversationID = e.conversationID
		this.conversationName = e.conversationName
		this.userID = getID(e.conversationID)
		console.log(e.conversationID, this.userID,'ididi');
		uni.setNavigationBarTitle({
			title: e.conversationName
		})

		this.keyboardHeight = uni.getStorageSync(cVersion + 'keyboardHeight') || 0
		this.minHeight = uni.getStorageSync(cVersion + 'minHeight') || 0

		this.$nextTick(async () => {
			windowHeight = uni.getSystemInfoSync().windowHeight
			this.getList()
		})
		this.getGiftList()
		uni.onKeyboardHeightChange(res => {
			const keyboardHeight = res.height;
			if (keyboardHeight === 0 && this.height > 0) {
				this.changeType = 1
				this.focus = false
				this.isMenu = true
			}
			if (this.keyboardHeight) return
			clearTimeout(this._timer);
			this._timer = setTimeout(() => {
				this.keyboardHeight = keyboardHeight
				this.height = keyboardHeight
				setTimeout(async () => {
					const bottom = await this.getHeight('#bottom')
					this.minHeight = windowHeight - bottom
					this.scroll_h = this.minHeight
					this.scrollToBottom()
					uni.setStorageSync(cVersion + 'keyboardHeight', this.keyboardHeight)
					uni.setStorageSync(cVersion + 'minHeight', this.minHeight)
				}, 300)
			}, 10)
		});
		//语音自然播放结束
		this.AUDIO.onEnded(res => {
			this.playMsg = { i: -1, play: -1 };
		});
		uni.$on('receivePeerMessage', message => {
			this.list = [...this.list, ...message]
			this.scrollToBottom(delay)
			//清除会话标记
			this.$im.clearConversationCount({ conversationID: this.conversationID })
		})
		
		this.getPhrasesList()
	},
	onHide() {
		this.hideDrawer()
	},
	computed: {
		uID() {
			return (id) => {
				if (!id) {
					return ''
				}
				return getID(id)
			}
		}
	},
	onUnload() {
		uni.removeStorageSync('current_conversationID')
		uni.hideKeyboard()
		uni.offKeyboardHeightChange(() => { });
	},
	methods: {
		// 常用语
		sendPhrases(e) {
			this.textPhrases = e
			this.sendEvent()
		},
		async getPhrasesList() {
			let res = await this.$api.post('Friend/GetChatContent');
			if (res.code == 0) {
				this.phrasesList = res.data
			}
		},
		// ---
		async GetUserType() {
			let res = await this.$api.post('Member/GetUserType', {
				CompanyID: 6003
			});
			if (res.code == 0) {
				this.viptype = res.data
			}
		},

		vipclose() {
			this.$refs['memberCard'].close()
			this.member_index = 0
		},
		async getList() {
			await this.$im.queryUsersInfo(this.conversationID) //优先执行获取用户头像
			this.list = await this.$im.queryHistoryMessage({ conversationID: this.conversationID })
			console.log(this.list,'-----------');
			await this.logicLoading() //页面逻辑处理
			await sleep(delay)
			this.initBotHeight = await this.getHeight('#bottom')
			this.scroll_h = windowHeight - this.initBotHeight
			this.scrollToBottom(0)
		},
		async getTechnician(UserID) {
			let res = await this.$api.post('Technicians/Get', { UserID })
			return res.data
		},
		isTechnician(covInfo) {
			return new Promise((resolve) => {
				const user = uni.getStorageSync('user')
				Promise.all([this.getTechnician(user.UserID), this.getTechnician(this.userID)]).then(res => {
					console.log(res[1]);
					if (res[0] || res[1]) {
						if (this.isSeek && res[1].Level === '教练') {
							setTimeout(() => {
								//教练问候语
								this.list.push({
									senderUserID: this.conversationID,
									type: 1,
									direction: 1,
									//预留字段greeting
									message: res[1].greeting ||
										"您好，很高兴能为你解答问题或提供帮助，请随时提出你的疑问或需求，我会尽快回复并提供专业的建议和指导。",
									userAvatarUrl: res[1].PhotoUrl,
									userName: res[1].TrueName
								})
								this.scrollToBottom(50)
							}, 1000)
							resolve(true)
						}
						if (this.isSeek && res[1].Level === '星助教') {
							setTimeout(() => {
								//星助教问候语
								this.list.push({
									senderUserID: this.conversationID,
									type: 200,
									subType: 153,
									direction: 1,
									userAvatarUrl: res[1].PhotoUrl,
									userName: res[1].TrueName
								})
								this.scrollToBottom(50)
							}, 1000)
							resolve(true)
						}
						resolve(true)
					}
					resolve(false)
				})
			})
		},
		async logicLoading() {
			let covInfo = await this.$api.post('User/GetUserInfo', {
				ID: this.userID
			});
			//是否是教练判断，只有一方存在教练，聊天不受限制
			if (await this.isTechnician(covInfo)) return true

			let friend = await this.$api.post('Friend/IsMyFriends', {
				FriendID: this.userID
			});
			this.isFriend = friend.data

			const user = uni.getStorageSync('user')
			if (user.UserType === '普通用户') {
				if (this.isFriend) {
					//发送开通会员提示
					this.list.push({ type: 200, subType: 150 }) //自定义开通会员提示
					return true
				}
				this.list.push({ type: 200, subType: 151 }) //非好友自定义添加好友提示
				return true
			}
			if (user.UserType === '黑金卡会员' || user.UserType === '黑金年卡会员') {
				//会员用户忽略非好友的功能限制
				this.isFriend = true
			}
			if (!this.isFriend) {
				this.list.push({ type: 200, subType: 151 }) //非好友自定义添加好友提示
				return true
			}

			//如果对方非会员发送赠送会员提示
			if (covInfo.data.UserType === '普通用户') {
				this.list.push({ type: 200, subType: 152 }) //赠送会员提示
			}
			return true
		},
		async getGiftList() {
			let res = await this.$api.post('Friend/GetGift');
			this.gift_list = res.data || [];
		},
		containsPhoneNumber(text) {
			const regex = /^1\d{10}$/;
			return regex.test(text);
		},
		getDate() {
			const today = new Date();
			const year = today.getFullYear();
			const month = String(today.getMonth() + 1).padStart(2, '0');
			const day = String(today.getDate()).padStart(2, '0');
			return `${year}${month}${day}`
		},
		sendEvent: throttle(async () => {
			if (that.content === '' && that.textPhrases == '') return
			const message = that.content || that.textPhrases
			that.textPhrases = ''
			const user = uni.getStorageSync('user')

			let words = ['微信', 'VX', 'weixin', 'wei', 'weix', 'wxin', 'xin', 'V', '加V', '加微', 'WECHAT', 'WX', '手机号',
				'手机', '联系方式', '电话', '联系电话', '联系', '电联', 'mobile', 'phone'
			];
			const checkText = message.replace(/\s/g, '')
			const checkWord = words.some(v => checkText.includes(v))
			if (checkWord) {
				uni.showToast({
					title: '消息内容存在违规',
					icon: 'none'
				})
				if (that.list[that.list.length - 1].subType !== 60) {
					
					const res = await that.$im.sendCustomMessage({
						conversationID: that.conversationID,
						subType: 60,
						message: JSON.stringify({
							checkMsg: message,
						})
					})
					if (res.code === 0) {
						that.list = [...that.list, ...res.data]
						that.scrollToBottom(50)
						return
					}
				}
				return
			}
			await that.$api.post('IM/Send',{
				ToUserID:that.userID,
				Content:message
			})
			await that.$api.post('IM/SaveSendLog',{
				ToUserID:that.userID,
				Content:message
			})
			// if (user.UserType == '普通用户') {
			// 	const currentDate = that.getDate()
			// 	const localDate = uni.getStorageSync('limitMsg') || ''
			// 	if (localDate === currentDate) {
			// 		if (that.list[that.list.length - 1].subType !== 150) {
			// 			that.list.push({ type: 200, subType: 150 }) //自定义开通会员提示
			// 			that.scrollToBottom(50)
			// 		}
			// 		uni.showToast({
			// 			title: '普通用户每天只能发送一条消息',
			// 			icon: 'none'
			// 		})
			// 		return
			// 	}
			// 	uni.setStorageSync('limitMsg', currentDate)
			// }
			that.content = ''
			const res = await that.$im.sendMessage({ conversationID: that.conversationID, message }, (data) => {
				that.list = [...that.list, ...that.$im.messageAttribute(data)]
				that.scrollToBottom(50)
			})
			console.log(res,'99999999');
			
			if (res.code === 6000221) {
				uni.showToast({
					title: '消息内容存在违规',
					icon: 'none'
				})
				return
			}
			if (res.code === 0) {
				// // #ifdef APP-PLUS
				// this.list = [...this.list, ...res.data]
				// this.scrollToBottom(50)
				// // #endif
				return
			}

			uni.showToast({
				title: '发送失败',
				icon: 'none'
			})
		}),
		//发送语音
		async sendRecord({ filePath, duration }) {
			const res = await this.$im.sendAudioMessage({
				conversationID: this.conversationID,
				filePath,
				duration
			}, (message) => {
				that.list = [...that.list, ...that.$im.messageAttribute(message)]
				that.scrollToBottom(50)
			}, (message, currentFileSize, totalFileSize) => { })
			if (res.code === 0) {
				// this.list = [...this.list, ...res.data]
				// this.scrollToBottom(50)
				return
			}
			uni.showToast({
				title: '发送失败',
				icon: 'none'
			})
		},
		//播放语音
		playAudio(url, i) {
			if (this.playMsg.i == i) {
				if (this.playMsg.play == 0) {
					this.playMsg = { i, play: 1 };
					return this.AUDIO.pause();
				} else {
					this.playMsg = { i, play: 0 };
					return this.AUDIO.play();
				}
			}
			this.playMsg = { i, play: 0 };
			this.AUDIO.src = url;
			this.$nextTick(function () {
				this.AUDIO.play();
			});
		},
		getImageInfo(path) {
			return new Promise(resolve => {
				uni.getImageInfo({
					src: path,
					success: (image) => {
						resolve(image)
					}
				});
			})
		},
		async sendImage(sourceType) {
			const res = await this.$im.sendImageMessage({
				conversationID: this.conversationID,
				sourceType,
			}, async (message) => {
				const image = await that.getImageInfo(message.fileLocalPath)
				message.thumbnailWidth = image.width < 200 ? image.width : 198
				message.thumbnailHeight = image.height * message.thumbnailWidth / image.width
				that.list = [...that.list, ...that.$im.messageAttribute(message)]
				that.scrollToBottom(50)
			}, (message, currentFileSize, totalFileSize) => { })
			if (res.code === 0) {
				const d = res.data[res.data.length - 1]
				const index = this.list.findIndex(x => x.localMessageID == d.localMessageID)
				if (index > -1) this.list[index].url = d.url
				return
			}
			console.log(res);
			uni.showToast({
				title: '发送失败',
				icon: 'none'
			})
		},
		async giveGift() {
			let d = this.gift_list[this.gift_index];
			const MessageId = Math.random().toString(36).substring(2, 14);
			let gift = await this.$api.post('Friend/SendGift', {
				Price: d.Price,
				GiftID: d.ID,
				GiftName: d.Name,
				GiftQty: 1,
				ToUserID: this.userID,
				EventID: d.ID,
				SendType: '赠送礼物',
				MessageId
			});
			let payment = await this.$api.post('Payment/PayV2', {
				total_fee: d.Price,
				EventType: '赠送礼物',
				EventID: gift.data,
				body: d.Name,
				SourcePage: 'single_chat',
				// #ifdef MP-WEIXIN
				PayChannel: "weixin",
				// #endif
				// #ifdef APP
				PayChannel: "app"
				// #endif
			});
			const sendIM = async () => {
				this.$refs['gift'].close()
				const res = await this.$im.sendCustomMessage({
					conversationID: this.conversationID,
					subType: 10,
					message: JSON.stringify({
						id: gift.data,
						MessageId,
						name: d.Name,
						icon: d.Icon,
						price: d.Price
					})
				})
				if (res.code === 0) {
					this.list = [...this.list, ...res.data]
					this.scrollToBottom(delay)
					return
				}
			}
			if (payment.data == 0) { //余额支付
				sendIM()
				return
			}
			let pay = JSON.parse(payment.data);
			uni.requestPayment({
				provider: 'wxpay',
				// #ifdef APP
				orderInfo: pay,
				// #endif
				// #ifdef MP-WEIXIN
				...pay,
				// #endif
				success(res) {
					sendIM()
				},
				fail(err) {
					that.$pv.msg('您已取消支付');
				}
			});
		},
		async addWX() {
			//判断加微信是否有优惠
			let promotion = await this.$api.post('Member/GetPromotion', {
				Item: '加微信'
			});
			if (promotion.data) {
				this.wx_price = promotion.data.Promotion;
			}
			//记录一下谁点击了微信
			this.$api.post('Friend/ViewWechatNo', {
				ToUserID: this.userID
			});
			const user = uni.getStorageSync('user')
			if (user.UserType === '普通用户' || user.UserType === '体验会员') {
				this.$refs['weixin'].open(); //普通用户弹窗
				return
			}
			this.$refs['WXAddMem'].open(); //会员权益
		},
		async sendWXIM() {
			this.$refs['WXAddMem'].close()
			let wx = await this.$api.post('Friend/FreeApplyWechatNo', {
				ToUserID: this.UserID
			});
			const res = await that.$im.sendCustomMessage({
				conversationID: that.conversationID,
				subType: 12,
				message: JSON.stringify({
					EventID: wx.data,
					remark: "加微信"
				})
			})
			if (res.code === 0) {
				that.list = [...that.list, ...res.data]
				that.scrollToBottom(delay)
				return
			}
		},
		//加微信单次支付
		async WXPayment() {
			let res = await this.$api.post('Friend/ApplyWechatNo', {
				ToUserID: this.userID,
			});
			const EventID = res.data
			let payment = await this.$api.post('Payment/PayV2', {
				total_fee: this.nv_price,
				EventType: '申请微信',
				EventID,
				body: '加微信',
				SourcePage: 'single_chat',
				// #ifdef MP-WEIXIN
				PayChannel: "weixin",
				// #endif
				// #ifdef APP
				PayChannel: "app"
				// #endif
			});
			const sendIM = async () => {
				this.$refs['WXAdd'].close()
				const res = await that.$im.sendCustomMessage({
					conversationID: that.conversationID,
					subType: 12,
					message: JSON.stringify({
						EventID,
						remark: "加微信"
					})
				})
				if (res.code === 0) {
					that.list = [...that.list, ...res.data]
					that.scrollToBottom(delay)
					return
				}
			}
			if (payment.data == 0) { //余额支付
				sendIM()
				return
			}
			let pay = JSON.parse(payment.data);
			uni.requestPayment({
				provider: 'wxpay',
				// #ifdef APP
				orderInfo: pay,
				// #endif
				// #ifdef MP-WEIXIN
				...pay,
				// #endif
				success(res) {
					sendIM()
				},
				fail(err) {
					that.$pv.msg('您已取消支付');
				}
			});
		},
		//会员支付
		async memberPayment() {
			let amount = 0
			let level = ''
			if (this.Issex == '女') {

				amount = this.member_index === 0 ? this.viptype[0].Discount == 1 ? this.viptype[0].Fee : this.viptype[0].PValue : this.viptype[1].Discount == 1 ? this.viptype[1].Fee : this.viptype[1].PValue
				level = this.member_index === 0 ? '金卡会员' : '黑金年卡会员'
			} else {
				amount = this.member_index === 0 ? this.viptype[0].Discount == 1 ? this.viptype[0].Fee : this.viptype[0].PValue : this.viptype[1].Discount == 1 ? this.viptype[1].Fee : this.viptype[1].PValue
				level = this.member_index === 0 ? '金卡会员' : '黑金年卡会员'
			}
			let payment = await this.$api.post('Payment/PayV2', {
				total_fee: amount,
				EventType: '会员升级',
				EventID: 0,
				body: level,
				SourcePage: 'single_chat',
				// #ifdef MP-WEIXIN
				PayChannel: "weixin",
				// #endif
				// #ifdef APP
				PayChannel: "app"
				// #endif
			});
			const sendIM = async () => {
				this.updateStorageUser()
				this.$refs['WXAdd'].close()
				let wx = await this.$api.post('Friend/FreeApplyWechatNo', {
					ToUserID: this.UserID
				});
				const res = await that.$im.sendCustomMessage({
					conversationID: that.conversationID,
					subType: 12,
					message: JSON.stringify({
						EventID: wx.data,
						remark: "加微信"
					})
				})
				if (res.code === 0) {
					that.list = [...that.list, ...res.data]
					that.scrollToBottom(delay)
					return
				}
			}
			if (payment.data == 0) { //余额支付
				sendIM()
				return
			}
			let pay = JSON.parse(payment.data);
			uni.requestPayment({
				provider: 'wxpay',
				// #ifdef APP
				orderInfo: pay,
				// #endif
				// #ifdef MP-WEIXIN
				...pay,
				// #endif
				success(res) {
					sendIM()
				},
				fail(err) {
					that.$pv.msg('您已取消支付');
				}
			});
		},
		//会员赠送
		async giveMember() {
			const amount = this.member_index === 0 ? this.viptype[0].Fee : this.viptype[1].Fee
			const level = this.member_index === 0 ? '金卡会员' : '黑金年卡会员'
			let payment = await this.$api.post('Payment/PayV2', {
				total_fee: amount,
				EventType: '赠送会员',
				EventID: this.userID,
				body: level,
				SourcePage: 'single_chat',
				// #ifdef MP-WEIXIN
				PayChannel: "weixin",
				// #endif
				// #ifdef APP
				PayChannel: "app"
				// #endif
			});
			const sendIM = async () => {
				this.$refs['memberCard'].close()
				const userID = uni.getStorageSync('imUserID')
				const res = await this.$im.sendCustomMessage({
					conversationID: this.conversationID,
					subType: 15,
					message: JSON.stringify({
						id: 1, //赠送的记录id
						status: 0,
						receiveUserID: this.conversationID,
						sendUserID: userID,
						member: {
							member_level: level,
							number: 1,
							price: amount,
						}
					})
				})
				if (res.code === 0) {
					this.list = [...this.list, ...res.data]
					this.scrollToBottom(delay)
					return
				}
			}
			if (payment.data == 0) { //余额支付
				sendIM()
				return
			}
			let pay = JSON.parse(payment.data);
			uni.requestPayment({
				provider: 'wxpay',
				// #ifdef APP
				orderInfo: pay,
				// #endif
				// #ifdef MP-WEIXIN
				...pay,
				// #endif
				success(res) {
					sendIM()
				},
				fail(err) {
					that.$pv.msg('您已取消支付');
				}
			});
		},
		async updateStorageUser() {
			let user = uni.getStorageSync('user')
			let res = await this.$api.post('User/GetUserInfo', {
				ID: user.UserID
			});
			user = res.data;
			uni.setStorageSync('user', user);
			this.$store.commit('setUser', user);
		},
		async customEvent(e, i) {
			const d = e.data
			switch (e.type) {
				case 'gift':
					this.list[i].receiptStatus = d.receiptStatus
					this.list[i].reactionType = d.reactionType
					//接口调用
					let res = await this.$api.post('Friend/AuditChatGift', {
						Status: 1,
						ID: d.gift.id,
						MessageId: d.gift.MessageId || ''
					});
					if (!res.data) {
						uni.showToast({
							title: '已经领取过啦',
							icon: 'none'
						})
						return
					};

					const gift = await this.$im.sendCustomMessage({
						conversationID: this.conversationID,
						subType: 11,
						message: JSON.stringify({
							id: 1, //赠送的记录id
							status: d.reactionType === 'accept' ? 0 : 10,
							receiveUserID: d.receiveUserID,
							sendUserID: d.sendUserID,
							gift: d.gift
						})
					})
					if (gift.code === 0) {
						this.list = [...this.list, ...gift.data]
						this.scrollToBottom(delay)
					}
					break;
				case 'wx':
					this.list[i].receiptStatus = d.receiptStatus
					this.list[i].reactionType = d.reactionType
					//接口调用
					const wx = await this.$im.sendCustomMessage({
						conversationID: this.conversationID,
						subType: 13,
						message: JSON.stringify({
							id: d.wx.EventID, //赠送的记录id
							status: d.reactionType === 'accept' ? 0 : 1,
							receiveUserID: d.receiveUserID,
							sendUserID: d.sendUserID,
						})
					})
					if (wx.code === 0) {
						this.list = [...this.list, ...wx.data]
					}
					// 发送微信号给对方
					if (d.reactionType === 'accept') {
						await sleep(200) //存在限频，需延迟
						let res = await this.$api.post('Friend/AuditWechatNo', {
							Status: 1,
							UserID: this.userID,
							ID: d.wx.EventID
						});

						if (res.data == '-99') {
							uni.showModal({
								title: '温馨提示',
								content: '您未设置微信，请先设置才能领取该礼物',
								cancelText: '取消',
								confirmText: "去设置",
								success(res) {
									if (res.confirm) {
										that.nav_to('/pages/user/user_edit');
									}
								}
							});
							return;
						}
						const wx_send = await this.$im.sendCustomMessage({
							conversationID: this.conversationID,
							subType: 14,
							message: JSON.stringify({
								wx_no: res.data
							})
						})
						if (wx_send.code === 0) {
							this.list = [...this.list, ...wx_send.data]
						}
					} else {
						await this.$api.post('Friend/AuditWechatNo', {
							Status: 99,
							UserID: this.userID,
							ID: d.wx.EventID
						});
					}
					this.scrollToBottom(delay)
					break;
				case 'friendAdd':
					uni.navigateTo({
						url: `/pages/user/add_friend?user_id=${this.userID}`
					})
					break;
				case 'memberGive':
					this.$refs['memberCard'].open()
					break;
				case 'robot':
					this.$im.sendMessage({ conversationID: this.conversationID, message: d.content }, (data) => {
						this.list = [...this.list, ...this.$im.messageAttribute(data)]
						this.scrollToBottom(50)
					})
					break;
				default:
					break;
			}
		},
		changeEvent() {
			this.isMenu = false
			this.changeType = this.changeType === 1 ? 2 : 1
			if (this.changeType === 2) {
				this.hideDrawer();
				return
			}
			this.openDrawer()
		},
		menuEvent() {
			this.isMenu = this.isMenu ? false : true
			if (this.isMenu) {
				this.changeType = 1
				this.focus = false
				uni.hideKeyboard()
				if (!this.keyboardHeight) return this.focus = true //暂时这么处理

				this.height = this.keyboardHeight
				this.scroll_h = this.minHeight
				this.scrollToBottom()
				return
			}
			this.focus = true
			this.height = this.keyboardHeight
			this.scroll_h = this.minHeight
		},
		openDrawer() {
			this.isMenu = false
			if (this.keyboardHeight) {
				this.focus = true
				this.height = this.keyboardHeight
				this.scroll_h = this.minHeight
				this.scrollToBottom()
			}
		},
		hideDrawer() {
			if (this.height === 0) return
			this.focus = false
			this.height = 0
			this.isMenu = false
			this.scroll_h = windowHeight - this.initBotHeight
			this.scrollToBottom()
			uni.hideKeyboard()
		},
		async linechange(e) {
			const { lineCount } = e.detail
			if (this.lineCount === lineCount) return
			this.lineCount = lineCount
			const height = await this.getHeight('#bottom')
			this.scroll_h = windowHeight - height
			this.scrollToBottom()
		},
		// 滚动至聊天底部
		async scrollToBottom(wait) {
			// this.scrollTop = this.scrollTop > 0 ? this.scrollTop + 0.01 : ''
			if (wait) await sleep(wait)
			let query = uni.createSelectorQuery().in(this);
			query.select('#msglistview').boundingClientRect();
			query.exec(async (res) => {
				if (res[0].height > this.scroll_h) {
					this.scrollTop = res[0].height - this.scroll_h + 50
				}
				if (this.loading) {
					await sleep(400)
					this.loading = false
				}
			})
		},
		getHeight(id) {
			return new Promise(resolve => {
				let query = uni.createSelectorQuery().in(this);
				query.select(id).boundingClientRect();
				query.exec((res) => {
					resolve(res[0].height)
				})
			})
		},
		getAudioWidth(length) {
			const len = length >= 50 ? 14 : length >= 40 ? 13 : length >= 30 ? 12 : length >= 20 ? 11 : length >= 10 ?
				10 : length
			return 140 + 15 * len
		},
		previewImage(url) {
			uni.previewImage({
				current: 0,
				urls: [url],
			});
		},
		copyText(str) {
			uni.setClipboardData({
				data: str,
				success() { }
			});
		},
		toRoute(url) {
			uni.navigateTo({
				url
			})
		}
	}
};
</script>

<style lang="scss" scoped>
@import "assets/chat.scss";
</style>